﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DxfFilesScan
{
    public partial class frmMain : Form
    {
        private const string outputs = "outputs";
        private string srcFolder;
        private string desFolderFull;
        private bool autoUpdate;
        public frmMain()
        {
            InitializeComponent();
        }

        public string SrcFolder
        {
            get
            {
                return srcFolder;
            }

            set
            {
                if (srcFolder != value && Directory.Exists(value))
                {
                    srcFolder = value;
                    txtSrcDir.Text = value;
                    string desFolder = Path.GetFileName(srcFolder);
                    string desFolderFull = Path.Combine(outputs, desFolder);
                    if (!Directory.Exists(desFolderFull))
                    {
                        Directory.CreateDirectory(desFolderFull);
                    }
                    FillDesDirsList();
                }
            }
        }

        private void ShowDesFolderInfo(string folder)
        {
            txtMsg.Text = $"{folder}下文件：{Environment.NewLine}";
            foreach (string f in Directory.GetFiles(folder, "*.*", SearchOption.AllDirectories))
            {
                string fn = f.Replace(folder, "");
                AppendMsg($"{fn}\t{new FileInfo(f).LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss")}");
            }
        }

        private void FillDesDirsList()
        {
            var lst = Directory.GetDirectories(outputs).Select(x => new DesItem(x)).ToList();

            cmbDestDir.DataSource = lst;
            var matchedItem = lst.First(x => x.DirName == Path.GetFileName(srcFolder));
            cmbDestDir.SelectedItem = matchedItem;
            ShowDesFolderInfo(matchedItem.FullDirName);
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dlg = new FolderBrowserDialog();
            dlg.Description = "指定A文件夹";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                SrcFolder = dlg.SelectedPath;
            }
        }

        private void txtSrcDir_DragEnter(object sender, DragEventArgs e)
        {
            DragDropEffects effects = DragDropEffects.None;
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                var path = ((string[])e.Data.GetData(DataFormats.FileDrop))[0];
                if (Directory.Exists(path))
                    effects = DragDropEffects.Copy;
            }

            e.Effect = effects;

        }

        private void txtSrcDir_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                var path = ((string[])e.Data.GetData(DataFormats.FileDrop))[0];
                if (Directory.Exists(path))
                {
                    SrcFolder = path;
                }
            }
        }

        private void AppendMsg(string msg)
        {
            txtMsg.Text += $"{msg}{Environment.NewLine}";
        }

        private bool CheckFolders()
        {
            desFolderFull = cmbDestDir.SelectedValue.ToString();
            if (Directory.Exists(SrcFolder) && Directory.Exists(desFolderFull))
            {
                return true;
            }
            else
            {
                AppendMsg("请先选择文件夹。");
                return false;
            }
        }

        private void AddRichText(RichTextBox tb, string s)
        {
            tb.SelectionStart = tb.TextLength;
            tb.SelectionLength = 0;

            tb.SelectionColor = Color.Black;
            string[] parts = DxfInfo.Split(s);
            tb.AppendText(parts[0]);
            tb.SelectionColor = Color.Green;
            tb.AppendText(parts[1]);
            tb.AppendText(Environment.NewLine);
        }

        private void DoCompare()
        {
            if (!CheckFolders())
                return;
            DxfComparer comparer = new DxfComparer(SrcFolder, desFolderFull);
            IList<string> added;
            IList<string> removed;
            comparer.CompareCurrentDirWithLastFile(autoUpdate, out added, out removed);

            foreach (string s in added)
            {
                AddRichText(txtAdd, s);
            }
            foreach (string s in removed)
            {
                AddRichText(txtRemove, s);
            }
        }

        private void btnCompare_Click(object sender, EventArgs e)
        {
            btnCompare.Enabled = false;
            txtAdd.Text = "";
            txtRemove.Text = "";
            txtMsg.Text = "";
            try
            {
                DoCompare();
                AppendMsg("比较完成。");
            }
            catch (Exception ex)
            {
                AppendMsg(ex.Message);
            }
            finally
            {
                btnCompare.Enabled = true;
            }


        }

        private void btnSave_Click(object sender, EventArgs e)
        {

        }

        private void chkUpdate_CheckedChanged(object sender, EventArgs e)
        {
            autoUpdate = chkUpdate.Checked;
        }

        private void txtSrcDir_TextChanged(object sender, EventArgs e)
        {
            bool valid = Directory.Exists(txtSrcDir.Text);
            txtSrcDir.ForeColor = valid ? Color.Black : Color.Red;
            if (valid)
            {
                SrcFolder = txtSrcDir.Text;
            }
        }
    }
}
